package com.xiaohong.file.controller;

import com.xiaohong.file.pojo.FastDFSFile;
import com.xiaohong.file.utils.FastDFSUtils;
//import com.xiaohong.user.feign.UserFeign;
import entity.Result;
import entity.StatusCode;
//import org.springframework.beans.factory.annotation.Autowired;
import org.csource.fastdfs.FileInfo;
import org.springframework.http.MediaType;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;

//import io.seata.spring.annotation.GlobalTransactional;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value ="/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result uploadFile(@RequestPart(value = "file") MultipartFile file) throws Exception {
        try {
            // 封装文件信息
            FastDFSFile fastDFSFile = new FastDFSFile(
                    file.getOriginalFilename(), // 文件名 1.jpg
                    file.getBytes(),  //文件字节数组
                    StringUtils.getFilenameExtension(file.getOriginalFilename()) //获取文件扩展名
            );

            String[] upLoad = FastDFSUtils.upLoad(fastDFSFile);
            // 拼接访问地址
//            String url = FastDFSUtils.getTrackerInfo()+"/"+upLoad[0]+"/"+upLoad[1];
//            String url = "http://file.xiaohong.work/"+upLoad[0]+"/"+upLoad[1];
            String url = "http://119.29.67.157:8080/"+upLoad[0]+"/"+upLoad[1];
            return new Result(true, StatusCode.OK,"文件上传成功",url);
        } catch (Exception e) {
            return new Result(false, StatusCode.ERROR,"文件上传失败");
        }
    }


    /**
     * 上传文件(带下标)
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value ="/index/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result uploadFile(@RequestPart(value = "file") MultipartFile file, @RequestParam(value = "index") Integer index) throws Exception {
        try {
            // 封装文件信息
            FastDFSFile fastDFSFile = new FastDFSFile(
                    file.getOriginalFilename(), // 文件名 1.jpg
                    file.getBytes(),  //文件字节数组
                    StringUtils.getFilenameExtension(file.getOriginalFilename()) //获取文件扩展名
            );

            String[] upLoad = FastDFSUtils.upLoad(fastDFSFile);
            // 拼接访问地址
//            String url = FastDFSUtils.getTrackerInfo()+"/"+upLoad[0]+"/"+upLoad[1];
//            String url = "http://file.xiaohong.work/"+upLoad[0]+"/"+upLoad[1];
            String url = "http://119.29.67.157:8080/"+upLoad[0]+"/"+upLoad[1];
            HashMap<String, Object> map = new HashMap<>();
            map.put("url", url);
            map.put("index",index);
            return new Result(true, StatusCode.OK,"文件上传成功",map);
        } catch (Exception e) {
            return new Result(false, StatusCode.ERROR,"文件上传失败");
        }
    }

    /**
     * 文件下载
     * @param fileUrl
     * @param downloadUrl
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/download")
    public Result downloadFile(String fileUrl, String downloadUrl) {
        try {
            fileUrl = fileUrl.split("xiaohong/")[1];
            InputStream downLoad = FastDFSUtils.downLoad("xiaohong", fileUrl);

            // 将文件写入本地磁盘
            //获取文件名
            String[] strings = fileUrl.split("/");
            if (!downloadUrl.endsWith("\\")){
                downloadUrl += "\\";
            }
            FileOutputStream outputStream = new FileOutputStream(downloadUrl+strings[strings.length-1]);

            //定义一个缓冲区
            byte[] buffer = new byte[1024];
            while (downLoad.read(buffer) != -1){
                outputStream.write(buffer);
            }
            outputStream.flush();
            outputStream.close();
            downLoad.close();

            return new Result(true, StatusCode.OK,"文件下载成功");
        }catch (Exception e){
            return new Result(true, StatusCode.OK,"文件下载失败或文件已删除");
        }

    }

    /**
     * 文件删除
     * @param fileUrl
     * @return
     * @throws Exception
     */
    @DeleteMapping(value = "/delete")
    public Result deleteFile(@RequestParam(value = "fileUrl") String fileUrl) {
        try {
            fileUrl = fileUrl.split("xiaohong/")[1];
            FastDFSUtils.deleteFile("xiaohong",fileUrl);
            return new Result(true, StatusCode.OK,"文件删除成功！");
        }catch (Exception e){
            return new Result(false, StatusCode.REMOTEERROR,"文件删除失败或文件已删除！");
        }
    }

    /**
     * 文件详情获取
     * @param url
     * @return
     */
    @GetMapping
    public Result getFileInfo(@RequestParam String url) {
        String[] strings = url.split("/");
        String groupName = strings[3];
        String remoteFi1eName = url.substring(url.lastIndexOf(groupName)+groupName.length()+1);
        try {
            FileInfo fileInfo = FastDFSUtils.getFileInfo(groupName, remoteFi1eName);
            return new Result(false, StatusCode.OK,"获取文件信息成功",fileInfo);
        }catch (Exception e) {
            return new Result(false, StatusCode.ERROR, "获取文件信息失败！");
        }
    }


    public static void main(String[] args) {
        String url = "http://file.xiaohong.work/xiaohong/M00/00/03/rBkJ6mBJ1mWAUD_SAABicztlTPA063.jpg";
        String[] strings = url.split("/");
        String groupName = strings[3];
        String remoteFi1eName = url.substring(url.lastIndexOf(groupName)+groupName.length()+1);
        System.out.println(groupName);
        System.out.println(remoteFi1eName);
    }


}
